#include <iostream>
#include <string>
#include <cerrno>  // errno.h
#include <cstring> // string.h
#include <unistd.h>
#include <cstdlib>
#include <sys/types.h>
#include <sys/wait.h>

void subprocess_write(int);
void fatherprocess_read(int);

// 子写父读
int main()
{
    // 创建管道
    int pipefd[2] = {0};
    int exitcode = pipe(pipefd);

    std::cout << "pipefd[0]: " << pipefd[0] << " pipefd[1]: " << pipefd[1] << std::endl;
    
    // 创建子进程
    int id = fork();

    // 子写父读
    if (id == 0)
    {
        std::cout << "子进程关闭不需要的fd, 准备发消息" << std::endl;
        sleep(1);
        // child
        // 关闭其他权限
        close(pipefd[0]);

        // 子进程写
        subprocess_write(pipefd[1]);

        close(pipefd[1]);
        exit(0);
    }
    std::cout << "父进程进程关闭不需要的fd, 准备收消息" << std::endl;
    sleep(1);
    // father
    // 关闭不需要的fd
    close(pipefd[1]);

    // 父进程读
    fatherprocess_read(pipefd[0]);

    close(pipefd[0]);

    pid_t rid = waitpid(id, nullptr, 0);
    if (rid > 0)
    {
        std::cout << "wait sucessfully\n" << std::endl;
    }
    return 0;
}

std::string other()
{
    static int cnt = 0;
    std::string messageid = std::to_string(cnt);
    cnt++;
    std::string stringid = std::to_string(getpid());
    std::string message = messageid + " my pid is " + stringid;

    return message;
}
void subprocess_write(int wfd)
{
    std::string message = "i am child: ";
    while (true)
    {
        std::string info = message + other();
        write(wfd, info.c_str(), info.size());// 写入管道的时候没有写入'\0'
        sleep(1);
    }
}
void fatherprocess_read(int rfd)
{
    char inbuffer[1024] = {0};
    while (true)
    {
        std::cout << "---------------------------------" << std::endl;
        ssize_t n = read(rfd, inbuffer, sizeof(inbuffer) - 1);
        if(n > 0)
        {
            inbuffer[n] = 0;
            std::cout  << inbuffer << std::endl;
        }
        else if (n == 0)
        {
            std::cout << "读端关闭" << std::endl;
            break;
        }
        else 
        {
            std::cout << "读入失败" << std::endl;
            break;
        }
    }
}